import Router from '@koa/router';
import db from '../mysqlHelper.js';
import logger from '../logger.js';
import response from '../response.js';
import moment from 'moment';
import md5 from 'md5';
import publicMethod from '../publicMethod.js';

const router = new Router();
router.prefix('/api');

async function autoAddOper(ctx, fatherid, name, type) {
    let role = await db.findOne('role', { is_sys: 1, type });
    if (role == null) {
        ctx.body = response.fail('没有对应的角色');
        return;
    }
    //随机生成一个八位的用户账号
    let account = "";
    //循环查询是否存在相同的账号
    let isExist = true;
    while (isExist) {
        account = Math.random().toString().slice(2, 10);
        isExist = await db.checkExist('oper', { account: account });
    }
    //插入操作员表
    let oper = {
        account: account,
        password: md5(account),
        role_id: role.id,
        name: name,
        type: type,// 强制加为服务商账号
        is_auto_create: 1,
        isp_id: fatherid,
        role_id: role.id,
        status: 1,
        create_oper: 'system',
        create_time: moment().format('YYYY-MM-DD HH:mm:ss')
    };
    console.log('auto add oper', JSON.stringify(oper))
    let res = await db.create('oper', oper);
    if (res instanceof Error) {
        logger.error(`isp create oper error :` + res.message);
        ctx.body = response.fail(`isp create oper error :` + res.message);
        return;
    }
    if (type == 1) {
        //更新所属服务商的操作员id
        let res = await db.update('isp', { account: account }, { id: fatherid });
        if (res instanceof Error) {
            logger.error(`isp update error :` + res.message);
            ctx.body = response.fail(`isp update error :` + res.message);
            return;
        }
    }
    else if (type == 2) {
        //更新所属项目的操作员id
        let res = await db.update('project', { account: account }, { id: fatherid });
        if (res instanceof Error) {
            logger.error(`project update error :` + res.message);
            ctx.body = response.fail(`project update error :` + res.message);
            return;
        }
    }

}

router.post('/:table/insert', async (ctx) => {
    let body = ctx.request.body;
    if (ctx.state.oper == null) {
        if (ctx.state.openid == null) {
            ctx.body = response.fail('请先登录');
            return;
        }
        else {
            ctx.body = response.fail('该token无插入数据的权限');
            return;
        }
    }
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let isExist = false;
    switch (ctx.params.table) {
        case 'role':
            if (body.role_name == null) {
                ctx.body = response.fail('缺少必填字段 角色名称');
                return;
            }
            if (body.role_value == null) {
                ctx.body = response.fail('缺少必填字段 角色值');
                return;
            }
            // isExist = await db.checkExist('role', { name: body.name });
            // if (isExist) {
            //     ctx.body = response.fail('相同级别相同名称的角色已存在');
            //     return;
            // }
            body.create_time = moment().format('YYYY-MM-DD HH:mm:ss');
            break;

        case 'dictionary_detial':
            if (body.name == null) {
                ctx.body = response.fail('缺少必填字段 字典详情名称');
                return;
            }
            isExist = await db.checkExist('dictionary_detial', { name: body.name });
            if (isExist) {
                ctx.body = response.fail('相同名称的数据字典详情已存在');
                return;
            }
            break;
        case 'enterprise':
            if (body.name == null) {
                ctx.body = response.fail('缺少必填字段 企业名称');
                return;
            }
            isExist = await db.checkExist('enterprise', { name: body.name });
            if (isExist) {
                ctx.body = response.fail('相同企业已存在');
                return;
            }
            break;
        case 'workers':
            if (body.account == null) {
                ctx.body = response.fail('缺少必填字段 帐号');
                return;
            }
            isExist = await db.checkExist('workers', { account: body.account });
            if (isExist) {
                ctx.body = response.fail('相同帐号的员工已存在');
                return;
            }
            if (body.password) {
                body.password = md5(body.password);
            }
            break;
        case 'evaluator':
            if (body.name == null) {
                ctx.body = response.fail('缺少必填字段 名称');
                return;
            }
            if (body.password) {
                body.password = md5(body.password);
            }
            break;
        case 'order_info':
            //生成12位数字订单号
            body.id = Math.random().toString().slice(2, 14);
            break;
        default:
            break;
    }
    let res = await db.create(ctx.params.table, body);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} create error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} create error :` + res.message);
        return;
    }

    switch (ctx.params.table) {
        case 'isp':
            await autoAddOper(ctx, res.insertId, body.name, 1);
            break
        case 'project':
            await autoAddOper(ctx, body.id, body.name, 2);
            break
        case 'charging_station':
            res = await publicMethod.updateChargeGuns(body.sn, body.type, body.guns_num, body.project_id);
            if (res.code == 0) {
                console.error(`更新充电桩信息出错 error :` + res.msg, `station_id:${body.id}`);
                ctx.body = response.fail(res.msg);
                return;
            }
            break;
        default:
            break;
    }
    ctx.body = response.success();

});
function getConditions(tbaleName, body) {
    let conditions = {};
    //根据不同的表获取表的主键用于后续的更新和删除
    switch (tbaleName) {
        case 'oper':
            if (body.account == null) {
                return { code: 0, conditions, msg: '缺少必填字段 account' };
            }
            conditions = { account: body.account };
            return { code: 1, conditions: conditions };
        case 'project_charge_ext':
            if (body.project_id == null) {
                return { code: 0, conditions, msg: '缺少必填字段 project_id' };
            }
            conditions = { project_id: body.project_id };
            return { code: 1, conditions: conditions };
        case 'charging_station':
            if (body.sn == null) {
                return { code: 0, conditions, msg: '缺少必填字段 sn' };
            }
            conditions = { sn: body.sn };
            return { code: 1, conditions: conditions };
        case 'bike_station':
            if (body.sn == null) {
                return { code: 0, conditions, msg: '缺少必填字段 sn' };
            }
            conditions = { sn: body.sn };
            return { code: 1, conditions: conditions };
        default:
            if (body.id == null) {
                return { code: 0, conditions, msg: '缺少必填字段 id' };
            }
            conditions = { id: body.id };
            return { code: 1, conditions: conditions };
    }
}

router.post('/:table/update', async (ctx) => {
    if (ctx.state.oper == null) {
        if (ctx.state.openid == null) {
            ctx.body = response.fail('请先登录');
            return;
        }
        else {
            ctx.body = response.fail('该token无修改数据的权限');
            return;
        }
    }
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions;
    let obj = await db.findOne(ctx.params.table, conditions);
    if (obj == null) {
        ctx.body = response.fail('要修改数据不存在');
        return;
    }
    // for (let key in body) {
    //     if (body[key] != undefined && body[key] != null) {
    //         obj[key] = body[key];
    //     }
    // }
    delete body.conditions;
    let guns_change = false;
    if (ctx.params.table == 'charging_station') {

        if (obj.guns_num != body.guns_num) {
            guns_change = true;
        }
    }

    res = await db.update(ctx.params.table, body, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} update error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} update error :` + res.message);
        return;
    }
    if (ctx.params.table == 'charging_station') {
        if (guns_change) {
            let res = await publicMethod.updateChargeGuns(body.id, obj.type, body.guns_num, obj.project_id);
            if (res.code == 0) {
                console.error(`更新充电桩信息出错 error :` + res.msg, `station_id:${body.id}`);
                ctx.body = response.fail(res.msg);
                return;
            }
        }
    }

    ctx.body = response.success();
});

router.post('/:table/remove', async (ctx) => {
    if (ctx.state.oper == null) {
        if (ctx.state.openid == null) {
            ctx.body = response.fail('请先登录');
            return;
        }
        else {
            ctx.body = response.fail('该token无删除数据的权限');
            return;
        }
    }
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions;
    res = await db.deleteRow(ctx.params.table, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} delete error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} delete error :` + res.message);
        return;
    }
    if (ctx.params.table == 'device') {
        memDB.deleteDevice({ sn: body.sn });
    }
    ctx.body = response.success();
});
router.post('/:table/getList', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        body = { limit: 10, offset: 0, direction: 'desc' };
    } else {
        if (!body.direction) body.direction = 'desc';
    }
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    try {
        //sql注入攻击检测
        publicMethod.validateRequestParams(body);
    } catch (error) {
        console.error('SQL Injection detected:', error.message, JSON.stringify(body));
        ctx.body = response.fail('SQL Injection detected: ');
        return;
    }

    let res = await db.findAll(ctx.params.table, body.conditions, body.orderBy, body.direction, body.limit, body.offset, body.areaArr, body.likeArr, body.leftJoinArr, body.inArr, body.dispColumn, body.customizeWhere);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} getList error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} getList error :` + res.message);
        return;
    }
    if (res.count) {
        ctx.body = response.success({ rows: res.rows, count: res.count });
        return;
    } else {
        ctx.body = response.success(res);
    }
});

router.post('/charging_station/batchAdd', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.type == null) {
        ctx.body = response.fail('缺少必填字段 type');
        return;
    }
    if (body.protocol == null) {
        ctx.body = response.fail('缺少必填字段 protocol');
        return;
    }
    if (body.max_power == null) {
        ctx.body = response.fail('缺少必填字段 max_power');
        return;
    }
    if (body.guns_num == null) {
        ctx.body = response.fail('缺少必填字段 guns_num');
        return;
    }
    if (body.num == null) {
        ctx.body = response.fail('缺少必填字段 num');
        return;
    }
    if (body.num <= 0) {
        ctx.body = response.fail('参数 num 错误');
        return;
    }
    let isExist = true;
    let snArr = [];
    for (let i = 0; i < body.num; i++) {
        let sn = '';
        while (isExist) {
            //生成12位数字sn
            sn = `${moment().format('YYMMDDHHmmss')}${Math.random().toString().slice(2, 4)}`;
            isExist = await db.checkExist('charging_station', { sn: sn });
            //检查snArr
            if (snArr.includes(sn)) {
                isExist = true;
            }
        }
        snArr.push(sn);
        isExist = true;
    }
    //开始启用事务批量写入
    let sqls = [];
    for (let i = 0; i < snArr.length; i++) {
        let charging_station = {
            sn: snArr[i],
            type: body.type,
            protocol: body.protocol,
            max_power: body.max_power,
            guns_num: body.guns_num,
            status: 0
        }
        sqls.push({ sql: `INSERT INTO charging_station SET ?`, param: charging_station });
        for (let j = 0; j < body.guns_num; j++) {
            let gun = {
                sn: snArr[i],
                type: body.type,
                no: j + 1,
                connect_vehcile: 0,
                gunStatus: 2,
                chargeStatus: 0
            }
            sqls.push({ sql: `INSERT INTO guns SET ?`, param: gun });
        }
    }
    let res = await db.transaction(sqls);
    if (res instanceof Error) {
        logger.error(`批量添加充电桩失败 error :` + res.message, `sn:${snArr}`);
        ctx.body = response.fail('批量添加充电桩失败');
        return;
    }
    ctx.body = response.success(snArr, '批量添加充电桩成功');
});

router.post('/vehicle/setDefault', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.phone == null) {
        ctx.body = response.fail('缺少必填字段 phone');
        return;
    }
    if (body.plate == null) {
        ctx.body = response.fail('缺少必填字段 plate');
        return;
    }
    let sqls = [];
    //去掉原有的默认车辆
    sqls.push({ sql: `UPDATE vehicle SET is_default=0 WHERE phone=?`, param: [body.phone] });
    //设置新的默认车辆
    sqls.push({ sql: `UPDATE vehicle SET is_default=1 WHERE phone=? and plate=?`, param: [body.phone, body.plate] });
    let res = await db.transaction(sqls);
    if (res instanceof Error) {
        logger.error(`设置默认车辆失败 error :` + res.message, `phone:${body.phone},plate:${body.plate}`);
        ctx.body = response.fail('设置默认车辆失败');
        return;
    }
    ctx.body = response.success();
});


export { router };
